package com.webmeeting.chat.wordchat.servlets;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.myframework.utils.logutil.WMLogger;
import com.myframework.utils.stringutil.StringUtil;
import com.webmeeting.chat.wordchat.bl.ChatRoom;
import com.webmeeting.chat.wordchat.dao.entities.User;
import com.webmeeting.chat.wordchat.events.WordChatMessageInbound;

public class LogoutServlet extends HttpServlet {

	private static final long	serialVersionUID	= 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		HttpSession session = req.getSession();
		String roomName = (String) session.getAttribute("roomName");
		User user = (User) req.getSession(true).getAttribute("user");
		if (null != user && !StringUtil.isEmpty(roomName)) {
			List<ChatRoom> rooms = WordChatInitServlet.getOnlineRoomList();
			for (ChatRoom room : rooms) {
				if (roomName.equals(room.getRoomName())) {
					List<WordChatMessageInbound> users = room.getUsers();
					for (int i = 0; i < users.size(); i++) {
						if (users.get(i).getCurrUser().getUsername().equals(user.getUsername())) {
							users.remove(i);
							break;
						}
					}
					break;
				}
			}
			WMLogger.debug("User: " + user.getUsername() + " logout the system.");
		}
		req.getSession(true).invalidate();
		RequestDispatcher nextPage = req.getRequestDispatcher(req.getContextPath() + "/index.xhtml");
		nextPage.forward(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		HttpSession session = req.getSession();
		String roomName = (String) session.getAttribute("roomName");
		User user = (User) req.getSession(true).getAttribute("user");
		if (null != user && !StringUtil.isEmpty(roomName)) {
			List<ChatRoom> rooms = WordChatInitServlet.getOnlineRoomList();
			for (ChatRoom room : rooms) {
				if (roomName.equals(room.getRoomName())) {
					List<WordChatMessageInbound> users = room.getUsers();
					for (int i = 0; i < users.size(); i++) {
						if (users.get(i).getCurrUser().getUsername().equals(user.getUsername())) {
							users.remove(i);
							break;
						}
					}
					break;
				}
			}
			WMLogger.debug("User: " + user.getUsername() + " logout the system.");
		}
		req.getSession(true).invalidate();
		RequestDispatcher nextPage = req.getRequestDispatcher(req.getContextPath() + "/index.xhtml");
		nextPage.forward(req, resp);
	}

}
